package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.client.AccountClient;
import com.woniu.commons.exception.VenueRuntimeException;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.RedisKey;
import com.woniu.commons.model.StateData;
import com.woniu.dao.YRecruitMapper;
import com.woniu.dao.YVenueBaseMapper;
import com.woniu.model.dto.RecruitPageDto;
import com.woniu.model.form.PageRecruitForm;
import com.woniu.model.model.YRecruit;
import com.woniu.model.model.YVenueBase;
import com.woniu.model.param.AddRecruitParam;
import com.woniu.model.param.PageParam;
import com.woniu.model.param.UpdateRecruitParam;
import com.woniu.model.param.VenueLoadMyRecruitParam;
import com.woniu.service.YRecruitService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sound.sampled.Port;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author EdisonLiu
 * @since 2024年05月23日
 */
@Service
public class YRecruitServiceImpl extends ServiceImpl<YRecruitMapper, YRecruit> implements YRecruitService {

    @Resource
    private YRecruitMapper recruitMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private AccountClient accountClient;
    @Resource
    private YVenueBaseMapper yVenueBaseMapper;

    /**
     * 场馆新增招聘信息
     * @param p 场馆新增招聘的信息
     * @return
     */
    @Override
    public Integer addRecruit(AddRecruitParam p) {

        RLock fairLock = redissonClient.getFairLock(RedisKey.addRecruitVenueIdLock(p.getVenueId()));
        RLock lock = redissonClient.getMultiLock(fairLock);
        Integer i = 0;
        try {
            // 尝试获取锁，最多等待20s
            boolean success = lock.tryLock(20, TimeUnit.SECONDS);
            if (success) {
                YRecruit recruit = BeanUtil.toBean(p, YRecruit.class);
                recruit.setRecruitState(StateData.RECRUIT_STATE_OK);
                i = recruitMapper.insert(recruit);


            } else {
                throw new Exception("服务器繁忙");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            lock.unlock();
        }
        return i;
    }

    @Override
    public Integer updateRecruit(UpdateRecruitParam p) {
        YRecruit recruit = BeanUtil.toBean(p, YRecruit.class);
        YRecruit recruit1 = recruitMapper.selectOne(new QueryWrapper<YRecruit>().eq("recruit_id", p.getRecruitId()));
        if (!recruit1.getVenueId().equals(recruit.getVenueId())){
            throw new VenueRuntimeException(3013,"非本场馆发布");
        }

        return recruitMapper.updateById(recruit);
    }

    @Override
    public Integer cancelRecruit(Integer recruitId, Integer venueId) {
        YRecruit recruit = recruitMapper.selectOne(new QueryWrapper<YRecruit>().eq("recruit_id", recruitId));
        if (!recruit.getVenueId().equals(venueId)){
            throw new VenueRuntimeException(3013,"非本场馆发布");
        }
        if (recruit.getRecruitState().equals(StateData.RECRUIT_STATE_CANCEL)){
            throw new VenueRuntimeException(3014,"招聘信息状态异常");
        }
        recruit.setRecruitState(StateData.RECRUIT_STATE_CANCEL);
        int i = recruitMapper.updateById(recruit);
        return i;
    }

    @Override
    public Page<YRecruit> pageRecruit(PageRecruitForm form) {
        form.setPageNum(form.getPageNum() == null ? 1 : form.getPageNum());
        form.setPageSize(form.getPageSize() == null ? 5 : form.getPageSize());
        Page<YRecruit> page = new Page<>(form.getPageNum(), form.getPageSize());
        QueryWrapper<YRecruit> wrapper = new QueryWrapper<>();
        if (form.getRecruitState() != null){
            if (form.getRecruitState().equals(StateData.RECRUIT_STATE_OK)){
                wrapper.eq("recruit_state",StateData.RECRUIT_STATE_OK);
            }else if (form.getRecruitState().equals(StateData.RECRUIT_STATE_CANCEL)){
                wrapper.eq("recruit_state",StateData.RECRUIT_STATE_CANCEL);
            }
        }
        if (form.getVenueId()!=null){
            wrapper.eq("venue_id",form.getVenueId());
        }
        Page<YRecruit> recruitPage = recruitMapper.selectPage(page, wrapper);
        return recruitPage;
    }

    @Override
    public Page<RecruitPageDto> pageAllRecruit(PageParam param) throws YogaException {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        //拼接条件
        QueryWrapper<YRecruit> wrapper = new QueryWrapper<YRecruit>();
        wrapper.ne("recruit_state",0);
        Page<YRecruit> recruitPage = recruitMapper.selectPage(new Page<YRecruit>(param.getPageNum(), param.getPageSize()), wrapper);

        Page<RecruitPageDto> page = new Page<>();
        page.setCurrent(recruitPage.getCurrent());
        page.setOptimizeCountSql(recruitPage.optimizeCountSql());
        page.setPages(recruitPage.getPages());
        page.setSearchCount(recruitPage.searchCount());
        page.setSize(recruitPage.getSize());
        page.setTotal(recruitPage.getTotal());

        ArrayList<RecruitPageDto> dto = new ArrayList<>();

        for (YRecruit recruit:recruitPage.getRecords()) {

            RecruitPageDto pageDto = BeanUtil.toBean(recruit, RecruitPageDto.class);

            //通过场馆ID查出场馆名字
            YVenueBase yVenueBase = yVenueBaseMapper.selectById(recruit.getVenueId());
            if (yVenueBase == null){
                throw new YogaException(500,"场馆不存在");
            }
            pageDto.setVenueName(yVenueBase.getVenueName());

            dto.add(pageDto);
        }
        page.setRecords(dto);
        return page;
    }


    /**
     * 场馆端查询自己发布了的招聘信息（+带条件搜索）
     * @param param
     * @return
     */
    @Override
    public Page<RecruitPageDto> VenueLoadMyRecruit(VenueLoadMyRecruitParam param) throws YogaException {

        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        //拼接条件
        QueryWrapper<YRecruit> wrapper = new QueryWrapper<YRecruit>();
        wrapper.ne("recruit_state",0);
        wrapper.like("recruit_title",param.getRecruitTitle());
        wrapper.eq("venue_id",param.getVenueId());
        Page<YRecruit> recruitPage = recruitMapper.selectPage(new Page<YRecruit>(param.getPageNum(), param.getPageSize()), wrapper);

        Page<RecruitPageDto> page = new Page<>();
        page.setCurrent(recruitPage.getCurrent());
        page.setOptimizeCountSql(recruitPage.optimizeCountSql());
        page.setPages(recruitPage.getPages());
        page.setSearchCount(recruitPage.searchCount());
        page.setSize(recruitPage.getSize());
        page.setTotal(recruitPage.getTotal());

        ArrayList<RecruitPageDto> dto = new ArrayList<>();

        for (YRecruit recruit:recruitPage.getRecords()) {

            RecruitPageDto pageDto = BeanUtil.toBean(recruit, RecruitPageDto.class);

            //通过场馆ID查出场馆名字
            YVenueBase yVenueBase = yVenueBaseMapper.selectById(recruit.getVenueId());
            if (yVenueBase == null){
                throw new YogaException(500,"场馆不存在");
            }
            pageDto.setVenueName(yVenueBase.getVenueName());

            dto.add(pageDto);
        }
        page.setRecords(dto);
        return page;
    }







}
